package com.redlion;

import java.util.Collection;
import java.util.Iterator;

import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.physics.box2d.util.Vector2Pool;

import android.util.Log;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.World;

public class radialHandler implements IUpdateHandler {

	private PhysicsWorld world;
	private Body planetBody;
	private Collection<Body> circles;
	private Vector2 gravityCenter;

	@Override
	public void onUpdate(float pSecondsElapsed) {
		// Update Physics World

		for (Body circle : circles) {
			// Get position of our current body in the iteration
			Vector2 position = Vector2Pool.obtain(circle.getPosition());
			// Get the distance between the two objects.
			Vector2 dir = Vector2Pool.obtain(position.sub(gravityCenter));
			// Vector2 d = position.sub(gravityCenter);
			// The further away the objects are, the weaker the gravitational
			// force is
			float force = 100.0f / dir.len2();
			// 150 can be changed to adjust the
			// amount of force
			Vector2 F = Vector2Pool.obtain(dir.nor().mul(force));
			// Finally apply a force on the body in the direction of the
			// "Planet"
			circle.applyForce(F.mul(-1), gravityCenter);
			Vector2Pool.recycle(position);
			Vector2Pool.recycle(dir);
			Vector2Pool.recycle(F);
		}
	}

	@Override
	public void reset() {
		Vector2Pool.recycle(gravityCenter);
	}

	public void setWorld(PhysicsWorld world) {
		this.world = world;
	}

	public void setFixture(Body planetBody) {
		this.planetBody = planetBody;
		gravityCenter = Vector2Pool.obtain(planetBody.getPosition());
	}

	public void setCircles(Collection<Body> circles) {
		this.circles = circles;
	}

}
